package controller

import (
	"github.com/doujunyu/gogo/job"
	"github.com/doujunyu/gogo/sql_aid"
	_ "github.com/lib/pq"
	"go_self/model"
	"go_self/server"
	"go_self/util"
)

// LoginByUsername 用户登录
func LoginByUsername(j *job.Job) {
	if j.Input["username"] == "" {
		j.JsonSuccess(nil, "账号不能为空")
		return
	}
	if j.Input["password"] == "" {
		j.JsonSuccess(j.Input, "密码不能为空")
		return
	}
	userSql, args := sql_aid.PgTable(model.TableByUser).Field("id", "status", "password").Where("username = ?", j.Input["username"]).ToSql()
	user, err := sql_aid.DataToMap(model.PgSql.Query(userSql, args...))
	if err != nil || len(user) == 0 {
		j.JsonError(nil, "账户不存在")
		return
	}
	if int(user[0]["status"].(int64)) != model.UserByStatusNormal {
		j.JsonError(nil, "账户已被禁用")
		return
	}

	if err = util.CheckHash(user[0]["password"].(string), j.Input["password"]); err != nil {
		j.JsonError(nil, "密码错误")
		return
	}
	data, err := server.UserLogin(user[0]["id"].(int64))
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess(data)
}

// RegisterByUsername 用户注册
func RegisterByUsername(j *job.Job) {
	if j.Input["username"] == "" {
		j.JsonError(nil, "用户名不能为空")
		return
	}
	if j.Input["password"] == "" {
		j.JsonError(j.Input, "密码不能为空")
		return
	}
	//进行注册
	userId, err := server.UserRegisterByUsername(j.Input["username"], j.Input["password"])
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	data, err := server.UserLogin(userId)
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess(data)
	return

}

// UserByHome 我的
func UserByHome(j *job.Job) {
	list := make(map[string]interface{})
	list["user"] = model.UserByInfo(j.GroupData["user_id"].(int64))
	list["is_admin"] = j.GroupData["is_admin"].(int)
	//list["shop_id"] = model.UserIdToShopId(j.GroupData["user_id"].(int64))
	j.JsonSuccess(list)
	return
}
